﻿using System.Collections.Generic;

namespace PhiStore.Util
{
    /// <summary>
    /// A collection of useful utilities for arrays (or collections)
    /// </summary>
    public static class ArrayUtil
    {
        /// <summary>
        /// Copies data from a collection to an array
        /// </summary>
        /// <typeparam name="TKey">Type of array</typeparam>
        /// <typeparam name="T">a collection with internal value type of TKey</typeparam>
        /// <param name="input">The collection from which the data comes</param>
        /// <returns>The array with data</returns>
        public static TKey[] CopyTo<TKey, T>(T input) where T : ICollection<TKey>
        {
            TKey[] result = new TKey[input.Count];
            input.CopyTo(result, 0);
            return result;
        }

        /// <summary>
        /// A variant of the Knuth Shuffle:
        /// http://en.wikipedia.org/wiki/Knuth_shuffle
        /// </summary>
        /// <typeparam name="T">Any value type</typeparam>
        /// <param name="input">Array to randomize</param>
        public static void Randomize<T>(T[] input)
        {
            for (int i = 0; i < input.Length; i++)
            {
                int toSwapWith = RandomGenerator.Integer(i, input.Length);
                if (toSwapWith != i)
                {
                    T p = input[i];
                    input[i] = input[toSwapWith];
                    input[toSwapWith] = p;
                }
            }
        }

    }
}
